package com.han.walkman.controller;

import com.han.walkman.entity.CaseEntity;
import com.han.walkman.entity.DataBackEntity;
import com.han.walkman.service.CaseService;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/5/10
 * @Desc:
 */
@RestController
@RequestMapping("/case")
public class CaseController {
    private final CaseService caseService;

    public CaseController(CaseService caseService) {
        this.caseService = caseService;
    }

    /**
     * 查询全部
     *
     * @return list
     */
    @GetMapping("/findAll")
    public List<CaseEntity> findAll() {
        return caseService.findAll();
    }

    /**
     * 分页查询
     *
     * @return list
     */
    @GetMapping("/findByKeyword")
    public DataBackEntity<Page<CaseEntity>> findByPage(int userId, String keyword, Integer type, Integer index, Integer size) {

        if (userId == -1) {
            return new DataBackEntity<>(0, "请获得授权后查看", null);
        }
        //构建搜索条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //忽略大小写
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        CaseEntity entity = new CaseEntity();
        if (type != 0) {
            entity.setOrgType(type);
        }
        entity.setTitle(keyword);
        Example<CaseEntity> entityExample = Example.of(entity, exampleMatcher);

        Pageable pageable = PageRequest.of(index, size);
        Page<CaseEntity> caseEntityPage = caseService.findAll(entityExample, pageable);
        return new DataBackEntity<>(1, "查询历史拜访记录成功", caseEntityPage);
    }

    @GetMapping("/findById")
    public CaseEntity findById(Integer id) {
        Optional<CaseEntity> entityOptional = caseService.findById(id);
        return entityOptional.orElse(null);
    }

    /**
     * 查询文件list
     *
     * @return 剔除掉不需要参数的list
     */
    @GetMapping("/findStarCase")
    public List<CaseEntity> findStarCase() {
        CaseEntity entity = new CaseEntity();
        entity.setStar(true);
        Example<CaseEntity> entityExample = Example.of(entity);
        return caseService.findAll(entityExample);
    }
}
